import * as http from 'http'
import * as os from 'os'
import 'reflect-metadata'
import * as WebSocket from 'ws'
import Router from './src/Router'
import UploadUtil from './src/utils/UploadUtil'
import SData from './src/utils/SData'

Router.init()
SData.init()

const server = http.createServer((req, res) => {
    if (req.method === 'OPTIONS') {
        res.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS, GET, POST, PUT, DELETE',
            'Access-Control-Allow-Headers': '*',
            'Access-Control-Max-Age': 86400,
            'Access-Control-Allow-Credentials': 'true'
        })
        res.end()
    } else {
        const contentType = req.headers['content-type']
        if (contentType && contentType.indexOf('multipart/form-data') !== -1) {
            Router.controller(req, res, {})
            return
        }

        const to404 = () => {
            res.writeHead(404, { 'Content-Type': 'text/plain' })
            res.end()
        }

        let requestData = ''

        req.on('data', (chunk) => {
            requestData += chunk
        })

        req.on('end', () => {
            if (req.headers) Router.controller(req, res, requestData)
            else {
                to404()
            }
        })
    }
})

const wss = new WebSocket.Server({ server, path: '/SubscribeHub' })

wss.on('connection', (ws, req) => {
    console.log(`WebSocket connection established for ${req.url}`)
    ws.send('Hello WebSocket Client!')
    ws.on('message', (message) => {
        console.log(`Received message from WebSocket client: ${message}`)
    })
})

const port = 3005
server.listen(port, () => {
    const ifaces = os.networkInterfaces()
    Object.keys(ifaces).forEach((ifname) => {
        let address
        ;(ifaces as any)[ifname].forEach((iface: any) => {
            if ('IPv4' !== iface.family || iface.internal !== false) {
                return
            }
            address = iface.address
        })
        console.log(`Server running at http://${address}:${port}/`)
    })
})
